<?php

?>



<div id="addFLDSForm-cont" class="hidden">
    <form class="well form-inline margin-horisontal well-small login" action="" method="POST" name="addFLDSForm" id="addFLDSForm">
        <fieldset>


            <input type="hidden" name="action" value="">
            <input type="hidden" id="flds_id" name="id" value="">
            <input type="hidden" id="flds_floor_id" name="floor_id" value="">

            <div class="control-group" id="cg-flds_tbl">
                <label class="control-label" for="flds_tbl">Таблица данных</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="flds_tbl" name="flds_tbl" value="">
                    <!--       data-provide="typeahead" data-items="4" data-source="<?php //echo Arr::getValue($params, 'tables', ''); ?>">-->
                </div>
                <span class="help-inline"></span>
            </div>






            <div class="control-group" id="cg-flds_sen">
                <div style="float: right;">
                    <button type="button" class="btn btn-success" id="addFLDSSen-open"><i class="icon-check icon-white"></i> Выбрать</button>
                </div>
                <label class="control-label" for="flds_sen">Датчики</label>
                <div class="clear_both"></div>
                <div class="controls">
                    <input type="hidden" id="flds_sen" name="flds_sen" value="">
                    <div id="flds_sen-view" class="well well-small " style="min-height: 40px; margin-bottom: 5px;"></div>
                </div>
                <span class="help-inline"></span>
            </div>


            <div class="control-group" id="cg-flds_whatsum">
                <label class="control-label" for="flds_whatsum">Столбец с данными</label>
                <div class="controls">
                    <select id="flds_whatsum" name="flds_whatsum" class="input-xlarge">

                    </select>
                    <span class="help-inline"></span>
                </div>
            </div>

            <div class="control-group" id="cg-flds_time_shift">
                <label class="control-label" for="flds_time_shift">Сдвиг времени поступления данных</label>
                <div class="controls">
                    <input type="text" class="input-small" id="flds_time_shift" name="flds_time_shift" maxlength="2" value="0"> часов
                </div>
                <span class="help-inline"></span>
            </div>


            <div class="control-group" id="cg-flds_use_timelimit">
                <label class="control-label" for="flds_use_timelimit">Анализировать данные в интервале</label>
                <div class="controls">
                    <select id="flds_use_timelimit" name="flds_use_timelimit" class="input-xlarge">
                        <option value="0" selected>Круглосуточно</option>
                        <option value="1">Указать значения</option>
                    </select>
                    <span class="help-inline"></span>
                </div>
            </div>

            <div class="control-group" id="cg-flds_time_min">

                <div class="controls  pull-left">
                    <label class="control-label" for="flds_time_min">c</label>
                    <select id="flds_time_min" name="flds_time_min" class="input-small">
                        <option value="00:00:00" selected>00:00</option>
                        <option value="01:00:00">01:00</option>
                        <option value="02:00:00">02:00</option>
                        <option value="03:00:00">03:00</option>
                        <option value="04:00:00">04:00</option>
                        <option value="05:00:00">05:00</option>
                        <option value="06:00:00">06:00</option>
                        <option value="07:00:00">07:00</option>
                        <option value="08:00:00">08:00</option>
                        <option value="09:00:00">09:00</option>
                        <option value="10:00:00">10:00</option>
                        <option value="11:00:00">11:00</option>
                        <option value="12:00:00">12:00</option>
                        <option value="13:00:00">13:00</option>
                        <option value="14:00:00">14:00</option>
                        <option value="15:00:00">15:00</option>
                        <option value="16:00:00">16:00</option>
                        <option value="17:00:00">17:00</option>
                        <option value="18:00:00">18:00</option>
                        <option value="19:00:00">19:00</option>
                        <option value="20:00:00">20:00</option>
                        <option value="21:00:00">21:00</option>
                        <option value="22:00:00">22:00</option>
                        <option value="23:00:00">23:00</option>
                        <option value="23:59:59">24:00</option>
                    </select>
                    <span class="help-inline" id="hi-flds_time_min"></span>
                </div>

                <div class="controls  pull-left">
                    <label class="control-label" for="flds_time_max">по</label>
                    <select id="flds_time_max" name="flds_time_max" class="input-small">
                        <option value="00:00:00" selected>00:00</option>
                        <option value="01:00:00">01:00</option>
                        <option value="02:00:00">02:00</option>
                        <option value="03:00:00">03:00</option>
                        <option value="04:00:00">04:00</option>
                        <option value="05:00:00">05:00</option>
                        <option value="06:00:00">06:00</option>
                        <option value="07:00:00">07:00</option>
                        <option value="08:00:00">08:00</option>
                        <option value="09:00:00">09:00</option>
                        <option value="10:00:00">10:00</option>
                        <option value="11:00:00">11:00</option>
                        <option value="12:00:00">12:00</option>
                        <option value="13:00:00">13:00</option>
                        <option value="14:00:00">14:00</option>
                        <option value="15:00:00">15:00</option>
                        <option value="16:00:00">16:00</option>
                        <option value="17:00:00">17:00</option>
                        <option value="18:00:00">18:00</option>
                        <option value="19:00:00">19:00</option>
                        <option value="20:00:00">20:00</option>
                        <option value="21:00:00">21:00</option>
                        <option value="22:00:00">22:00</option>
                        <option value="23:00:00">23:00</option>
                        <option value="23:59:59">24:00</option>
                    </select>
                    <span class="help-inline" id="hi-flds_time_max"></span>
                </div>
                <div class="clear_both"></div>
            </div>





            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="addFLDSForm-submit"><i class="icon-ok icon-white"></i> Сохранить</button>
                <button type="reset" class="btn btn-danger" id="addFLDSForm-cancel"><i class="icon-remove icon-white"></i> Отменить</button>
            </div>
        </fieldset>
    </form>
</div>











<script>

     function FLDSWrongFields(wf) {
        wf = wf || {};
        var wf_count = 0;

        var cgdivs = Elm.addFLDSForm.find('div.error').removeClass('error');
        cgdivs.find('span.help-inline').empty();

        for(var id in wf) {
            if (!wf.hasOwnProperty(id)) continue;
            var msg = wf[id];

            var cg = $('#cg-flds_'+id).addClass('error');
            cg.find('span.help-inline').html(msg);
            wf_count++;
        }
        return wf_count;
    }




    function FLDSRequestTables(callback) {
        if(Elm.addFLDSForm.tablesSet) {
            if (typeof(callback()) == 'function') callback();
            return;
        }
        
        var send = {
            action: '<?php echo ACTIONS::DATA_TABLES_GET; ?>'
        };
        jsonRequest(
            'views.php?showTables',
            send,

            function(data) {
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }

                    if (data.hasOwnProperty('response_data') && data.response_data) {
                        var resp = data.response_data;
                        if (resp.hasOwnProperty('tables')) {
                            $('#flds_tbl').autocomplete({source: resp.tables});
                            Elm.addFLDSForm.tablesSet = true;
                            if (typeof(callback()) == 'function') callback();
                        }
                    }
                }
                else {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        FLDSRequestTables(callback);
                    };
                }
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
    }




    function FLDSFormOpen (ds, action) {
        debug();

        if (!ds.hasOwnProperty('p')) return;
        FLDSWrongFields();

        for(var i in ds.p) {
            if (!ds.p.hasOwnProperty(i)) continue;

            $('#flds_'+i).val(ds.p[i]);
        }
        refreshWhatsum(function() { $('#flds_whatsum').val(ds.p['whatsum']);} );
        refreshSensorsField(ds);


        Elm.addFLDSForm.get(0).action.value = action;


        Elm.addFLDSForm.
            off('submit').
            submit(function() {
                submitFLDSForm(ds);
                return false;
            });

        FLDSRequestTables(function() {
            Elm.addFLDS.dialog("open");
            bindSensorsButton(ds);
            refreshFLDSForm();
            refreshSensorsField(ds);
        });
    }


function refreshSensorsField(ds) {
    if (ds.p.sen.gReplace(' ','')) {
        $('#flds_sen-view').html(ds.p.sen.gReplace(',',', '));
        $('#flds_sen').val(ds.p.sen.gReplace(',',', '));
    }
    else {
        $('#flds_sen-view').html('Все');
        $('#flds_sen').val('');
    }

    //console.log(ds);
}


function bindSensorsButton(ds) {
    var checkedSen = ds.p.sen.gReplace(' ','').split(',');

    $('#addFLDSSen-open').click(function(){
        addSenFormOpen(
            $('#flds_tbl').val(),

            function() {
                addSenFormMarkSensors(checkedSen);
            },

            function(sensors) {
                //console.log(sensors);
                ds.p.sen = sensors.join(', ');
                refreshSensorsField(ds);
            }
        );

        return false;
    });
}



function submitFLDSForm(ds) {
    FLDSWrongFields();
    var send = [];
    for (var i in ds.p) {
        if (!ds.p.hasOwnProperty(i)) continue;

        var f = $('#flds_'+i);
        if (f) send[i] = f.val() || '';
        else send[i] = ds.p[i] || '';
    }
    //console.log(ds,send);
    //var send = Elm.addVwForm.serialize();
    //progressButton();

    //console.log(send);
    jsonRequest(
        'views.php?flds',
        $.extend({},send,{action:Elm.addFLDSForm[0].action.value}),

        function(data) {
            FLDSWrongFields({});
            if(checkSession(data)) {
                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }

                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;
                    if (resp.hasOwnProperty('wrongFields')) {
                        var wf = FLDSWrongFields(resp.wrongFields);
                        if (wf*1>0) return;
                    }

                    if (resp.hasOwnProperty('insertedId')) {
                        send['id'] = resp.insertedId;
                    }
                    if (
                        Elm.addFLDSForm.hasOwnProperty('successCallback')
                        && (typeof(Elm.addFLDSForm.successCallback) == 'function')
                    ) {
                        var cb = Elm.addFLDSForm.successCallback;
                        Elm.addFLDSForm.successCallback = function() {};
                        cb(send);
                    }
                }
                closeFLDSDialog();
            }
            else Elm.loginFormModal.dialog('open');

        },

        function() {
            FLDSWrongFields({});
            uiAlert('Ошибка соединения','Error');
        }
    );
    return;
}



function requestFields(tbl, callback) {
    callback = callback || function(fields) {};

    jsonRequest(
        'views.php?tblFields',
        {
            action  : '<?php echo ACTIONS::DATA_TABLE_FIELDS; ?>',
            table   : tbl
        },

        function(data) {
            if(checkSession(data)) {
                if (!data.state) {
                    //uiAlert(data.message,'Error');
                    return;
                }

                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;

                    if (resp.hasOwnProperty('fields')) {
                        if (typeof(callback) == 'function') callback(resp.fields);
                    }
                }
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    requestFields(tbl, callback);
                };
            }
        },

        function() {
            //uiAlert('Ошибка соединения','Error');
        }
    );
}









function refreshWhatsum(onDone) {
    onDone = onDone || function() {};
    var tbl = $('#flds_tbl').val();
    var sel = $('#flds_whatsum');

    var whatsum = sel.val();
    sel.empty();

    if (!tbl) return;

    requestFields(tbl, function(fields) {
        sel.append('<option value="" selected>Выберите столбец</option>');
        var senFound = false;
        for (var i in fields) {
            if (fields.hasOwnProperty(i)) sel.append('<option value="'+fields[i]+'" selected>'+fields[i]+'</option>');
            if (fields[i].toUpperCase() == 'SEN') senFound = true;
        }
        sel.val(whatsum);
        if (senFound) $('#addFLDSSen-open').removeAttr('disabled');
        else $('#addFLDSSen-open').attr('disabled', 'disabled');
        if (typeof(onDone) == 'function') onDone(fields);
    });
}




function closeFLDSDialog() {
    Elm.addFLDS.dialog('close');
}

function refreshFLDSForm () {
    if ($('#flds_use_timelimit').val()*1 > 0) {
        $('#cg-flds_time_min').show();
    }
    else $('#cg-flds_time_min').hide();
}





    $(function() {
        Elm.addFLDS = $('#addFLDSForm-cont');
        Elm.addFLDSForm = $('#addFLDSForm');
        Elm.addFLDSForm.successCallback = function(data) {};
        Elm.addFLDSForm.tablesSet = false;

        $('#flds_tbl').autocomplete({
            source:[],
            minLength: 5,
            change: function() { refreshWhatsum(); }
        });

        $('#addFLDSForm-cancel').click(function(){
            closeFLDSDialog();
            return false;
        });




        Elm.addFLDS.dialog({
            width       : 350,
            modal       : true,
            resizable   : false,
            title       : "Источник данных",
            autoOpen    : false,
            buttons     : {}
        }).removeClass('hidden');

        Elm.addFLDSForm.change(function() {
            refreshFLDSForm ();
        });

    });

</script>